/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.modules.autocode.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * ClassName:XmlUtil.java <br/>
 * Date: 2015年11月4日 <br/>
 * 
 * @author Mr.Xiao
 * @version 1.0
 */
public class XmlUtil {
	public static void saveObject2Xml(Object obj, OutputStream ous) {
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
			marshaller.marshal(obj, ous);
		} catch (JAXBException e) {
			e.printStackTrace();
		}finally{
			try {
				ous.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static Object getObjectFromXml(Class cls , InputStream ins) {
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(cls);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			return unmarshaller.unmarshal(ins);
		} catch (JAXBException e) {
			e.printStackTrace();
		}finally{
			try {
				ins.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
